package org.grayrabbit.cloud.core.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.grayrabbit.cloud.core.handler.Handler;
import org.grayrabbit.cloud.core.rpc.Argument;
import org.grayrabbit.cloud.core.rpc.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MessageHandler extends IoHandlerAdapter {
	private final static Logger LOGGER = LoggerFactory.getLogger(MessageHandler.class);
	private Handler handler;
	public MessageHandler(Handler handler){
		this.handler = handler;
	}
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		super.sessionOpened(session);
		session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
		LOGGER.debug("Mina session is opened");
	}


	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		  session.close(true);
		  LOGGER.debug("Mina session is caught,the session is closed!");
		  LOGGER.error("Mina 异常:",cause);
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		if(message instanceof Argument){
			Argument argument = (Argument) message;
			LOGGER.debug("Argument {}",argument);
			Result result = this.handler.handle(argument);
			session.write(result);
		}else{
			LOGGER.debug("Revc message is {}",message);
		}
		
	}

}
